import { NetWorthRecord, Product } from '../types/product';

/**
 * 分析净值数据，计算相关指标
 */
export interface NetWorthAnalysis {
  latestValue: number;
  latestDate: string;
  earliestValue: number;
  earliestDate: string;
  totalGrowth: number;      // 总涨幅
  growthRate: number;       // 涨幅比例
  annualizedRate: number;   // 年化收益率
  volatility: number;       // 波动率
  maxDrawdown: number;      // 最大回撤
  recordCount: number;      // 记录数量
  daysCount: number;        // 天数
}

/**
 * 分析净值历史数据
 * @param records 净值记录数组
 * @returns 净值分析结果
 */
export const analyzeNetWorthHistory = (records: NetWorthRecord[]): NetWorthAnalysis | null => {
  if (!records || records.length < 2) {
    return null;
  }

  // 按日期降序排序
  const sortedRecords = [...records].sort((a, b) => 
    new Date(b.date).getTime() - new Date(a.date).getTime()
  );

  const latestRecord = sortedRecords[0];
  const earliestRecord = sortedRecords[sortedRecords.length - 1];

  const latestValue = latestRecord.value;
  const latestDate = latestRecord.date;
  const earliestValue = earliestRecord.value;
  const earliestDate = earliestRecord.date;

  // 计算总涨幅和涨幅比例
  const totalGrowth = latestValue - earliestValue;
  const growthRate = (totalGrowth / earliestValue) * 100;

  // 计算天数
  const daysCount = Math.round(
    (new Date(latestDate).getTime() - new Date(earliestDate).getTime()) / (1000 * 60 * 60 * 24)
  );

  // 计算年化收益率
  const annualizedRate = daysCount > 0 
    ? (Math.pow(latestValue / earliestValue, 365 / daysCount) - 1) * 100
    : 0;

  // 计算波动率
  let volatility = 0;
  if (sortedRecords.length > 2) {
    const dailyReturns = [];
    for (let i = 0; i < sortedRecords.length - 1; i++) {
      const current = sortedRecords[i].value;
      const next = sortedRecords[i + 1].value;
      const dailyReturn = (current - next) / next;
      dailyReturns.push(dailyReturn);
    }

    // 计算标准差
    const mean = dailyReturns.reduce((sum, val) => sum + val, 0) / dailyReturns.length;
    const variance = dailyReturns.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / dailyReturns.length;
    volatility = Math.sqrt(variance) * Math.sqrt(252) * 100; // 年化波动率
  }

  // 计算最大回撤
  let maxDrawdown = 0;
  let peak = sortedRecords[sortedRecords.length - 1].value;
  
  for (let i = sortedRecords.length - 2; i >= 0; i--) {
    const current = sortedRecords[i].value;
    if (current > peak) {
      peak = current;
    } else {
      const drawdown = (peak - current) / peak;
      maxDrawdown = Math.max(maxDrawdown, drawdown);
    }
  }

  return {
    latestValue,
    latestDate,
    earliestValue,
    earliestDate,
    totalGrowth,
    growthRate,
    annualizedRate,
    volatility,
    maxDrawdown: maxDrawdown * 100,
    recordCount: sortedRecords.length,
    daysCount
  };
};

/**
 * 格式化百分比
 * @param value 数值
 * @param digits 小数位数
 * @returns 格式化后的百分比字符串
 */
export const formatPercent = (value: number, digits: number = 2): string => {
  return `${value.toFixed(digits)}%`;
};

/**
 * 格式化净值
 * @param value 净值
 * @returns 格式化后的净值字符串
 */
export const formatNetWorth = (value: number): string => {
  return value.toFixed(6);
};